package com.zhongpengcheng.controller.user;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.cglib.CglibUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.zhongpengcheng.blog.enums.ResultCodeEnum;
import com.zhongpengcheng.blog.exception.UserException;
import com.zhongpengcheng.blog.pojo.dto.UserDTO;
import com.zhongpengcheng.blog.pojo.po.UserQueryPO;
import com.zhongpengcheng.blog.service.UserService;
import com.zhongpengcheng.blog.dao.pojo.db.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 用户接口，提供user相关的增删改查操作
 *
 * @author zhongpengcheng
 * @date 2021/08/13 16:39
 **/
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Qualifier("userIdGenerator")
    @Autowired
    private Snowflake userIdGenerator;


    /**
     * 根据用户名查询用户
     * @param userName 用户名
     * @return 用户对象
     */
    @GetMapping("/user/{userName}")
    public UserDTO getUserByName(@PathVariable String userName) throws UserException {
        UserDO user = userService.getUserByUserName(userName);
        if (user == null) {
            throw new UserException(ResultCodeEnum.USER_ACCOUNT_DOES_NOT_EXIST);
        }
        return CglibUtil.copy(userService.getUserByUserName(userName), UserDTO.class);
    }

    /**
     * 多条件联合查询user
     */
    @GetMapping("/user")
    public UserDTO getUser(@RequestBody UserQueryPO po) throws UserException {
        UserDO user = userService.getOne(Wrappers.<UserDO>lambdaQuery()
                .eq(UserDO::getUserId, po.getUserId())
                .eq(UserDO::getUsername, po.getUsername())
                .eq(UserDO::getNickName, po.getNickName()));
        if (user == null) {
            throw new UserException(ResultCodeEnum.USER_NOT_EXIST);
        }
        return CglibUtil.copy(user, UserDTO.class);
    }

    /**
     * 分页查询用户
     * @param po 查询参数
     * @return 分页对象
     */
    @GetMapping("/users")
    public Page<UserDTO> listUsers(UserQueryPO po) {
        // #1 查询到初始的page
        Page<UserDO> page = userService.page(Page.of(po.getCurrent(), po.getSize()), Wrappers.<UserDO>lambdaQuery()
                .eq(UserDO::getUserId, po.getUserId())
                .or().eq(UserDO::getUsername, po.getUsername())
                .or().eq(UserDO::getNickName, po.getNickName()));
        // #2 拿到page中的数据
        List<UserDO> users = page.getRecords();
        // #3 构造DTO的page
        Page<UserDTO> pageDTO = PageDTO.of(page.getCurrent(), page.getSize(), page.getTotal(), page.searchCount());
        // #4 user判空
        if (users == null) {
            return pageDTO;
        }
        // #5 DO->DTO
        List<UserDTO> userDTOS = CglibUtil.copyList(users, UserDTO::new);
        // #6 转换后的DTO置入DTO的page
        return pageDTO.setRecords(userDTOS);
    }

    @PostMapping("/user/{username}/{salt}")
    public void addRandomUser(@PathVariable String salt, @PathVariable String username) throws UserException {
        UserDO user = userService.getUserByUserName(username);
        if (user != null) {
            throw new UserException(ResultCodeEnum.USERNAME_HAS_EXISTS);
        }
        MD5 md5 = MD5.create();
        String password = md5.digestHex(username + salt);
        UserDO randomUser = UserDO.builder()
                .userId(userIdGenerator.nextIdStr())
                .username(username + IdUtil.randomUUID().substring(0, 6))
                .password(password)
                .salt(salt)
                .nickName(username)
                .build();

        userService.save(randomUser);
    }
}
